<template>
  <static-content-wrapper
      style="width: 100%;"
      :designer="designer" :field="field" :design-state="designState"
      :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
      :sub-form-row-index="subFormRowIndex" :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId">
    <el-form-item style="width: 100%;"  :label="field.options.label">
      <el-table
          ref="elTables"
          :data="fieldModel"
          style="width: 100% !important;">
        <el-table-column
            v-for="item in field.options.tablesOBJ"
            :key="item.dataKey"
            :prop="item.dataKey"
            :label="item.title"
            v-slot="scope"
            width="180">
<!--          这里如何自定义为input输入框-->
          <template >
            <el-input v-model="scope.row[item.dataKey]" :disabled="item.disabled"></el-input>
          </template>
        </el-table-column>
      </el-table>
        <span>{{field.options.defaultValue}}</span>
      <el-button @click="btn">添加一行</el-button>
      <el-button @click="getData">获取数据</el-button>
    </el-form-item>
  </static-content-wrapper>
</template>

<script>
import StaticContentWrapper from '@/components/form-designer/form-widget/field-widget/static-content-wrapper'
import emitter from '@/utils/emitter'
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin"
import {deepClone} from "@/utils/util";

export default {
  name: "tables-widget",
  componentName: 'FieldWidget',  // 必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false
    },

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: ''
    },
  },
  watch: {
    'field.options.tablesOBJ': {
      handler(newValue) {
        console.log('field.options.tablesOBJ 变化了:', newValue);

        // 创建一个新的 tableData 数组，逐行处理
        let updatedTableData = [];

        // 遍历现有的 tableData 行
        this.tableData.forEach(row => {
          let newRow = {};

          // 遍历新的 newValue，保留已有的值，并添加新列
          newValue.forEach(item => {
            newRow[item.dataKey] = row[item.dataKey] || '';
          });

          updatedTableData.push(newRow);
        });

        // 如果有新增列，添加新的空数据行
        if (newValue.length > this.tableData[0].length) {
          let newRow = {};
          newValue.forEach(item => {
            newRow[item.dataKey] = '';
          });
          updatedTableData.push(newRow);
        }

        // 更新 tableData 和 spanData
        this.tableData = updatedTableData;
        this.spanData = newValue.map(item => item.dataKey);

        // console.log('更新后的tableData', this.tableData);
        // console.log('spanData', this.spanData);
      },
      deep: true, // 监听嵌套对象的变化
      immediate: true // 立即执行 handler
    }
  },
  data() {
    return {
      tableData: [
        {name1719904802: '测试1', name1719904805: '测试2', name1719904811: '测试3'}
      ],
      spanData:[],
      fieldModel: null,
    }
  },
  components: {
    StaticContentWrapper,
  },
  created() {
    this.registerToRefList()
    this.initEventHandler()
    // console.log('打印', this.field)
  },
  mounted(){
    console.log(this.field,"11111111111111");
  },
  beforeDestroy() {
    this.unregisterFromRefList()
    this.initFieldModel()
  },
  methods: {
    initFieldModel() {
      if (!this.field.formItemFlag) {
        return
      }
      if (!!this.subFormItemFlag && !this.designState) {  //SubForm子表单组件需要特殊处理！！
        let subFormData = this.formModel[this.subFormName]
        if (((subFormData === undefined) || (subFormData[this.subFormRowIndex] === undefined) ||
                (subFormData[this.subFormRowIndex][this.field.options.name] === undefined)) &&
            (this.field.options.defaultValue !== undefined)) {
          this.fieldModel = this.field.options.defaultValue
          subFormData[this.subFormRowIndex][this.field.options.name] = this.field.options.defaultValue
        } else if (subFormData[this.subFormRowIndex][this.field.options.name] === undefined) {
          this.fieldModel = null
          subFormData[this.subFormRowIndex][this.field.options.name] = null
        } else {
          this.fieldModel = subFormData[this.subFormRowIndex][this.field.options.name]
        }

        /* 主动触发子表单内field-widget的onChange事件！！ */
        setTimeout(() => {  //延时触发onChange事件, 便于更新计算字段！！
          this.handleOnChangeForSubForm(this.fieldModel, this.oldFieldValue, subFormData, this.subFormRowId)
        }, 800)
        this.oldFieldValue = deepClone(this.fieldModel)

        this.initFileList()  //处理图片上传、文件上传字段

        return
      }

      if ((this.formModel[this.field.options.name] === undefined) &&
          (this.field.options.defaultValue !== undefined)) {
        this.fieldModel = this.field.options.defaultValue
      } else if (this.formModel[this.field.options.name] === undefined) {  //如果formModel为空对象，则初始化字段值为null!!
        this.formModel[this.field.options.name] = null
      } else {
        this.fieldModel = this.formModel[this.field.options.name]
      }
      this.oldFieldValue = deepClone(this.fieldModel)
      this.initFileList()  //处理图片上传、文件上传字段
    },
    // handleCloseCustomEvent() {
    //   if (this.field.options.onClose) {
    //     let changeFn = new Function(this.field.options.onClose)
    //     changeFn.call(this)
    //   }
    // }
    btn(){
      let newRow = {};
      this.spanData.forEach(dataKey => {
        newRow[dataKey] = '';
      });

      // 将新行添加到 tableData
      this.tableData.push(newRow);
      // console.log('提交数据',this.tableData)
      // console.log('查看tablesOBJ',this.field.options.tablesOBJ)
    },
    getData(){
      alert(JSON.stringify(this.tableData))
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__body-wrapper{
  .el-table__body{
    width: 100% !important;
    .el-table__cell{
      min-height: 40px;
    }
  }
}
::v-deep .el-table__header-wrapper{
  .el-table__header{
    width: 100% !important;
  }
  .el-table__cell{
    min-height: 40px;
  }
}
</style>
